package com.project.lk.nurseapp.nurse;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.lidong.photopicker.PhotoPickerActivity;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.base.BaseApi;
import com.project.lk.nurseapp.base.BaseApp;
import com.project.lk.nurseapp.base.UrlContants;
import com.project.lk.nurseapp.common.socket.SocketService;
import com.project.lk.nurseapp.common.view.bluetooth.BleManager;
import com.project.lk.nurseapp.common.view.chat.EmojiManager;
import com.project.lk.nurseapp.common.view.chat.IMMessage;
import com.project.lk.nurseapp.common.view.chat.MessageAdapter;
import com.project.lk.nurseapp.common.view.chat.MessageInputToolBox;
import com.project.lk.nurseapp.common.view.chat.OnOperationListener;
import com.project.lk.nurseapp.common.view.chat.voice.AudioRecorderButton;
import com.project.lk.nurseapp.common.view.chat.voice.MediaPlayerManager;
import com.project.lk.nurseapp.common.websocket.IMsgInfo;
import com.project.lk.nurseapp.common.websocket.MsgBean;
import com.project.lk.nurseapp.home.MainActivity;
import com.project.lk.nurseapp.home.usermsg.model.PostFileHintBean;
import com.project.lk.nurseapp.login.model.HintBean;
import com.project.lk.nurseapp.nurse.model.GetIMItemBean;
import com.project.lk.nurseapp.nurse.presenter.INurseView;
import com.project.lk.nurseapp.nurse.presenter.NursePresenter;
import com.project.lk.nurseapp.utils.AddPhoto;
import com.project.lk.nurseapp.utils.AppManager;
import com.project.lk.nurseapp.utils.MediaUtils;
import com.project.lk.nurseapp.utils.MessageCreateUtils;
import com.project.lk.nurseapp.utils.PopWindowManager;
import com.project.lk.nurseapp.utils.SharedPreferencesUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.project.lk.nurseapp.utils.UserInfoUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.lidong.photopicker.ImageCaptureManager.REQUEST_TAKE_PHOTO;
/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class NurseActivity extends BaseActivity implements INurseView {


    @BindView(R.id.messageListview)
    ListView messageListview;
    @BindView(R.id.messageInputToolBox)
    MessageInputToolBox messageInputToolBox;
    private String login = "";
    private Intent service;
    private NursePresenter presenter;
    private String httpUrl;
    private String sessionId = "";

    IMMessage imMessage = new IMMessage();
    List<IMMessage> mList = new ArrayList<>();
    private String contentText = "";
    private MessageAdapter mAdapter;

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
//        startService(new Intent(this,JobCastielService.class)); //开启服务提醒的服务
        if (!TextUtils.equals((String) SharedPreferencesUtils.getParam("socketAddress", ""), "")) {
            String socketAddress = (String) SharedPreferencesUtils.getParam("socketAddress", "");
            bind("", socketAddress);
        }
        login = getIntent().getStringExtra("login");
        if (TextUtils.equals(login, "login")) {
            presenter = new NursePresenter(this);
//            presenter.getFirstIM(UrlContants.GET_IM_URL,);
            imMessage.setContent("当前处于在线模式");
            imMessage.setDirect("");
            imMessage.setSenderType(BaseApi.nurse_send_type);
            imMessage.setMsgType(BaseApi.text_type);
            imMessage.setSenderHeadImg("");
            imMessage.setSenderNickName("提示");
            imMessage.setSenderId("");
            imMessage.setSessionId("");
            imMessage.setTime(String.valueOf(new Date().getTime()));
            mList.add(imMessage);
        } else {
            imMessage.setContent("当前处于离线模式");
            imMessage.setDirect("");
            imMessage.setSenderType(BaseApi.nurse_send_type);
            imMessage.setMsgType(BaseApi.text_type);
            imMessage.setSenderNickName("提示");
            imMessage.setSenderHeadImg("");
            imMessage.setSenderId("");
            imMessage.setSessionId("");
            imMessage.setTime(String.valueOf(new Date().getTime()));
            mList.add(imMessage);
        }
        initMessage();
    }

    private void initMessage() {

        // mList.add(message);
        mAdapter = new MessageAdapter(this, mList);
        messageListview.setAdapter(mAdapter);
        messageInputToolBox.setListView(messageListview);
        if (mList.size() != 0) {
            messageInputToolBox.scrollToBottom();
        }
        messageInputToolBox.hide();
        messageListview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                messageInputToolBox.hide();
                return false;
            }
        });
        messageInputToolBox.setSessionId((String) SharedPreferencesUtils.getParam("sessionId", ""));

        mAdapter.setOnEventListenter(new MessageAdapter.ItemEvent() {
            @Override
            public void showVipMsg() {  //创建一个vip的消息提示框
                IMMessage message = new IMMessage();
                message.setContent("请选择付费医师");
                message.setDirect("vip");
                message.setSenderType(BaseApi.nurse_send_type);
                message.setMsgType(BaseApi.text_type);
                message.setSenderHeadImg("");
                message.setSenderNickName("提示");
                message.setSenderId("");
                message.setSessionId("");
                message.setTime(String.valueOf(new Date().getTime()));
                notifyList(message);
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        initMessageInputToolBox();
        BleManager.init().initialize();
        setCommentPopwind();
    }

    /*刷新页面列表*/
    public void notifyList(IMMessage imMessage) {
        mList.add(imMessage);
        mAdapter.notifyDataSetChanged();
        if (mList.size() != 0) {
            messageInputToolBox.scrollToBottom();
        }
    }

    //初始化输入框
    Gson gson = new Gson();

    private void initMessageInputToolBox() {
        messageInputToolBox.setItemEvent();
        messageInputToolBox.setOnOperationListener(new OnOperationListener() {

            @Override
            public void send(String content) {
                if (TextUtils.equals((String) SharedPreferencesUtils.getParam("sessionId", ""), "")) {
                    if (presenter != null) {
                        presenter.getFirstIM(UrlContants.GET_IM_URL, "1", content);
                        contentText = content;
                        IMMessage imMessage = MessageCreateUtils.sendTextMsg(contentText, "",
                                BaseApi.user_send_type, new UserInfoUtils().getHeadImg()
                                , (String) SharedPreferencesUtils.getParam("sessionId", ""),
                                new UserInfoUtils().getNickName(), new UserInfoUtils().getAccountId());
                        notifyList(imMessage);
                    }
                } else {
                    //TODO:正常发消息
//                    String msgJson = MessageCreateUtils.getWebJson(gson, content, BaseApi.text_type, BaseApi.user_send_type);
//                    Log.e("MLOG",msgJson);
                    if (presenter != null) {
                        presenter.sendMsg(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.SEND_MSG_URL, (String) SharedPreferencesUtils.getParam("sessionId", "")
                                , content, BaseApi.text_type);
//                    mBinder.getService().sendMsg(msgJson);
                        IMMessage imMessage = MessageCreateUtils.sendTextMsg(content, "",
                                BaseApi.user_send_type, new UserInfoUtils().getHeadImg()
                                , (String) SharedPreferencesUtils.getParam("sessionId", ""),
                                new UserInfoUtils().getNickName(), new UserInfoUtils().getAccountId());
                        notifyList(imMessage);
                    }


                }

            }

            //发送表情
            @Override
            public void selectedFace(EmojiManager.Entry content) {

                EditText messageEditText = messageInputToolBox.getMessageEditText();
                Editable mEditable = messageEditText.getText();
                int start = messageEditText.getSelectionStart();
                int end = messageEditText.getSelectionEnd();
                start = (start < 0 ? 0 : start);
                end = (start < 0 ? 0 : end);
                mEditable.replace(start, end, content.getText());
            }

            @Override
            public void selectedFuncation(int index) {

            }

        });


        messageInputToolBox.setItemEvent();

        //回调声音放置在列表里
        messageInputToolBox.setVoiceItemEvent(new AudioRecorderButton.AudioFinishRecorderCallBack() {
            @Override
            public void onFinish(long seconds, final String filePath) {
                if (presenter != null) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            presenter.postFileData(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.POST_FILE_URL
                                    , filePath, BaseApi.audio_type);
                        }
                    }, 1000);
                }
                if (presenter != null) {
                    IMMessage imMessage = MessageCreateUtils.sendAudioMsg(filePath, "",
                            BaseApi.user_send_type, new UserInfoUtils().getHeadImg()
                            , (String) SharedPreferencesUtils.getParam("sessionId", ""),
                            new UserInfoUtils().getNickName(), new UserInfoUtils().getAccountId());
                    notifyList(imMessage);
                }

//                notifyList();
            }
        });
        messageInputToolBox.setFaceData();


    }

    Handler handler = new Handler();
    List<String> mPhotoList;
    private static final int REQUEST_CAMERA_CODE = 2;

    private static final int REQUEST_VIDEO_CODE = 100;
    private static final int RESULT_VIDEO_CODE = 101;

    //回调图片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择相册照片
                case REQUEST_CAMERA_CODE:

                    ArrayList<String> mImageList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    //TODO:相册的图片回调
                    Log.d("MLOG", mImageList.get(0).toString());

                    for (int i = 0; i < mImageList.size(); i++) {
                        String path = mImageList.get(i);
                        File file = new File(path);
                        // 创建图片消息
                        if (presenter != null) {
                            presenter.postFileData(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.POST_FILE_URL
                                    , file.getPath(), BaseApi.image_type);
                            IMMessage imMessage = MessageCreateUtils.sendImageMsg(file.getPath(), "",
                                    BaseApi.user_send_type, new UserInfoUtils().getHeadImg()
                                    , (String) SharedPreferencesUtils.getParam("sessionId", ""),
                                    new UserInfoUtils().getNickName(), new UserInfoUtils().getAccountId());
                            notifyList(imMessage);
                        }

                    }
//                    setPhoto(mImageList,null);
//                    mAdapter.setImageList((ArrayList<String>) mPhotoList);
                    break;
                // 拍照
                case REQUEST_TAKE_PHOTO:
                    String photoPath = AddPhoto.captureManager.getCurrentPhotoPath();
                    if (photoPath != null) {
                        AddPhoto.captureManager.galleryAddPic();
                        // 照片地址
                        String imagePaht = AddPhoto.captureManager.getCurrentPhotoPath();
                        Log.d("MLOG", imagePaht);
                        //TODO:拍照的图片回调
                        File file = new File(imagePaht);
                        //发送图标消息
                        if (presenter != null) {
                            presenter.postFileData(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.POST_FILE_URL
                                    , file.getPath(), BaseApi.image_type);
                            IMMessage imMessage = MessageCreateUtils.sendImageMsg(file.getPath(), "",
                                    BaseApi.user_send_type, new UserInfoUtils().getHeadImg()
                                    , (String) SharedPreferencesUtils.getParam("sessionId", ""),
                                    new UserInfoUtils().getNickName(), new UserInfoUtils().getAccountId());
                            notifyList(imMessage);
                        }

//                        setPhoto(null,imagePaht);
//                        mAdapter.setImageList((ArrayList<String>) mPhotoList);
                    }
                    break;
                case REQUEST_VIDEO_CODE:
                    String videoPath = data.getStringExtra("video");
                    String imgPath = data.getStringExtra("imgPath");
//                        ToastUtils.showShortToast(path);
                    if (presenter != null) {
                        presenter.postFileData(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.POST_FILE_URL
                                , videoPath, BaseApi.video_type);
                        IMMessage imMessage = MessageCreateUtils.sendVideoMsg(videoPath, "",
                                BaseApi.user_send_type, new UserInfoUtils().getHeadImg()
                                , (String) SharedPreferencesUtils.getParam("sessionId", ""),
                                new UserInfoUtils().getNickName(), new UserInfoUtils().getAccountId());
                        notifyList(imMessage);
                    }

                    break;

            }
        }

    }

    // 处理返回照片地址
    private void setPhoto(ArrayList<String> paths, String imagePath) {
        if (paths != null) {
            mPhotoList.addAll(paths);
        }
        if (imagePath != null) {
            mPhotoList.add(imagePath);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaPlayerManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaPlayerManager.resume();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_nurse;
    }


    @OnClick({R.id.msg_list, R.id.nurse_menu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.msg_list:   //消息记录
                if (TextUtils.equals(login, "login")) {
                    startActivity(new Intent(this, ChatListActivity.class));
                } else {
                    ToastUtils.showShortToast("当前是离线模式,无法查看消息记录");
                }

                break;
            case R.id.nurse_menu: //个人首页
                startActivity(new Intent(this, MainActivity.class)
                        .putExtra("login", login));
                break;
        }
    }

    private SocketService.WsBinder mBinder;

    public SocketService getBinder() {
        return mBinder.getService();
    }

    MyConn myConn;

    //处理绑定连接
    class MyConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //转换成MyBinder类型
            mBinder = (SocketService.WsBinder) service;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    //绑定服务
    public void bind(String wsUrl, String socketAddress) {
//        service = new Intent(this , WebSocketService.class);
//        service.putExtra("wsUrl",wsUrl+new UserInfoUtils().getUsername()+"/"+new UserInfoUtils().getAccountId());
        service = new Intent(this, SocketService.class);
        service.putExtra("socketAddress", socketAddress);
        startService(service);
        myConn = new MyConn();
        bindService(service, myConn, BIND_AUTO_CREATE);
    }

    @Override
    public void getIMSuccess() {  //连接websocket
        if (presenter != null) {
            List<GetIMItemBean> imItemBeanList = presenter.getIMItemBeanList();
            if (imItemBeanList != null && imItemBeanList.size() != 0) {
                String wsUrl = imItemBeanList.get(0).getWsUrl();
                httpUrl = imItemBeanList.get(0).getHttpUrl();
                sessionId = imItemBeanList.get(0).getSessionId();
                String socketAddress = imItemBeanList.get(0).getSocketAddress();
                SharedPreferencesUtils.setParam("socketAddress", socketAddress);
                SharedPreferencesUtils.setParam("sessionId", sessionId);
                SharedPreferencesUtils.setParam("httpUrl", httpUrl);
                SharedPreferencesUtils.setParam("wsUrl", wsUrl);
                messageInputToolBox.setSessionId((String) SharedPreferencesUtils.getParam("sessionId", ""));

                bind(wsUrl, socketAddress);
            }
        }

    }

    @Override
    public void getIMFail() {

    }

    @Override
    public void videoSuccess() {
        if (presenter != null) {
            List<PostFileHintBean> videoList = presenter.getVideoList();
            if (videoList != null && videoList.size() != 0) {
//                String msgJson = MessageCreateUtils.getWebJson(gson, videoList.get(0).getUrl(), BaseApi.image_type, BaseApi.user_send_type);
//                Log.e("MLOG",msgJson);
                presenter.sendMsg(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.SEND_MSG_URL, (String) SharedPreferencesUtils.getParam("sessionId", "")
                        , videoList.get(0).getUrl(), BaseApi.video_type);
//                mBinder.getService().sendMsg(msgJson);
            }
        }
    }

    @Override
    public void videoFail() {


    }

    @Override
    public void audioSuccess() {

        if (presenter != null) {
            List<PostFileHintBean> audioList = presenter.getAudioList();
            if (audioList != null && audioList.size() != 0) {
//                String msgJson = MessageCreateUtils.getWebJson(gson, audioList.get(0).getUrl(), BaseApi.image_type, BaseApi.user_send_type);
//                Log.e("MLOG",msgJson);
//                mBinder.getService().sendMsg(msgJson);
                presenter.sendMsg(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.SEND_MSG_URL, (String) SharedPreferencesUtils.getParam("sessionId", "")
                        , audioList.get(0).getUrl(), BaseApi.audio_type);
            }
        }
    }

    @Override
    public void audioFail() {

    }

    @Override
    public void imgSuccess() {

        if (presenter != null) {
            List<PostFileHintBean> imgList = presenter.getImgList();
            if (imgList != null && imgList.size() != 0) {
//                String msgJson = MessageCreateUtils.getWebJson(gson, imgList.get(0).getUrl(), BaseApi.image_type, BaseApi.user_send_type);
//                Log.e("MLOG",msgJson);
//                mBinder.getService().sendMsg(msgJson);

                presenter.sendMsg(SharedPreferencesUtils.getParam("httpUrl", "") + UrlContants.SEND_MSG_URL, (String) SharedPreferencesUtils.getParam("sessionId", "")
                        , imgList.get(0).getUrl(), BaseApi.image_type);
            }

        }
    }

    @Override
    public void imgFail() {

    }

    @Override
    public void sendVideoSuccess() {

    }

    @Override
    public void sendVideoFail() {
        sessionId = (String) SharedPreferencesUtils.getParam("sessionId", "");
        if (presenter != null) {
            List<HintBean> hintList = presenter.getHintList();
            if (hintList != null && hintList.size() != 0) {
                if (hintList.get(0).getInfo().contains("已结束")) {
                    SharedPreferencesUtils.setParam("sessionId", "");
//                    SharedPreferencesUtils.setParam("socketAddress","");
                    PopWindowManager.showAsLocationWindow(praentView, commentContentView
                            , commentPopupWindow, R.id.comment_popwind_layout);
                }
            }
        }
    }

    @Override
    public void sendAudioSuccess() {

    }

    @Override
    public void sendAudioFail() {
        Log.e("MLOG", ">>>>>>>>>>>>>");
        sessionId = (String) SharedPreferencesUtils.getParam("sessionId", "");
        if (presenter != null) {
            List<HintBean> hintList = presenter.getHintList();
            if (hintList != null && hintList.size() != 0) {
                if (hintList.get(0).getInfo().contains("已结束")) {
                    SharedPreferencesUtils.setParam("sessionId", "");
//                    SharedPreferencesUtils.setParam("socketAddress","");
                    PopWindowManager.showAsLocationWindow(praentView, commentContentView
                            , commentPopupWindow, R.id.comment_popwind_layout);
                }
            }
        }
    }

    @Override
    public void sendImgSuccess() {

    }

    @Override
    public void sendImgFail() {
        sessionId = (String) SharedPreferencesUtils.getParam("sessionId", "");
        if (presenter != null) {
            List<HintBean> hintList = presenter.getHintList();
            if (hintList != null && hintList.size() != 0) {
                if (hintList.get(0).getInfo().contains("已结束")) {
                    SharedPreferencesUtils.setParam("sessionId", "");
//                    SharedPreferencesUtils.setParam("socketAddress","");
                    PopWindowManager.showAsLocationWindow(praentView, commentContentView
                            , commentPopupWindow, R.id.comment_popwind_layout);
                }
            }
        }


    }

    @Override
    public void sendTextSuccess() {

    }

    @Override
    public void sendTextFail() {
        Log.e("MLOG", "fail>>>>>>>>>>>>>>>");
        sessionId = (String) SharedPreferencesUtils.getParam("sessionId", "");
        if (presenter != null) {
            List<HintBean> hintList = presenter.getHintList();
            if (hintList != null && hintList.size() != 0) {
                if (hintList.get(0).getInfo().contains("已结束")) {
                    SharedPreferencesUtils.setParam("sessionId", "");
//                    SharedPreferencesUtils.setParam("socketAddress","");

                }
            }
        }
//        PopWindowManager.

    }

    View praentView;
    View commentContentView;
    PopupWindow commentPopupWindow;
    EditText commentEdit;
    List<CommentStartBean> startList;
    int starPosition;

    //设置弹窗
    private void setCommentPopwind() {
        praentView = LayoutInflater.from(this).inflate(R.layout.activity_msg_list, null);
        commentContentView = LayoutInflater.from(this).inflate(R.layout.comment_popwind_layout, null);
        commentPopupWindow = new PopupWindow(commentContentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

        ImageView cancelBut = (ImageView) commentContentView.findViewById(R.id.cancel_but);
        commentEdit = (EditText) commentContentView.findViewById(R.id.comment_edit);
        Button commentBut = (Button) commentContentView.findViewById(R.id.comment_but);
        RecyclerView commentRecyclerView = commentContentView.findViewById(R.id.comment_rv);
        startList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            CommentStartBean bean = new CommentStartBean();
            startList.add(bean);
        }

        final CommentStartAdapter adapter = new CommentStartAdapter(startList, this);
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL);
        commentRecyclerView.setAdapter(adapter);
        commentRecyclerView.setLayoutManager(manager);

        adapter.setItemEvent(new CommentStartAdapter.ItemEventListenter() {
            @Override
            public void start(int position) {
                Log.e("MLOG", position + ">>>>>>>>>>>>>>>");
                starPosition = position;
                for (int i = 0; i < startList.size(); i++) {
                    if (i <= position) {
                        startList.get(i).setStart(true);
                    } else {
                        startList.get(i).setStart(false);
                    }
                }
                adapter.setmList(startList);
                adapter.notifyDataSetChanged();
            }
        });

        //点击事件
        setEvent(cancelBut, commentBut, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.cancel_but: //取消
                        commentPopupWindow.dismiss();
                        break;
                    case R.id.comment_but:  //评价
                        if (!TextUtils.isEmpty(commentEdit.getText())) {
                            presenter.evaluateChat(UrlContants.EVALUATE_SESSION_URL,
                                    (String) SharedPreferencesUtils.getParam("sessionId", "")
                                    , String.valueOf(starPosition), commentEdit.getText().toString());
                        } else {
                            presenter.evaluateChat(UrlContants.EVALUATE_SESSION_URL
                                    , (String) SharedPreferencesUtils.getParam("sessionId", "")
                                    , String.valueOf(starPosition), "");
                        }
                        commentPopupWindow.dismiss();
                        break;
                }
            }
        });
    }

    //设置点击事件
    private void setEvent(ImageView cancelBut, Button commentBut, View.OnClickListener listener) {
        cancelBut.setOnClickListener(listener);
        commentBut.setOnClickListener(listener);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMsgInfo(IMsgInfo iMsgInfo) {
        MsgBean data = iMsgInfo.getData();
        if (TextUtils.equals(data.getSenderNickName(), "0")) {
            data.setSenderNickName("提示");
        }
        IMMessage imMessage;
        if (TextUtils.equals(data.getMsgType(), "-1")
                || TextUtils.equals(data.getMsgType(), "5")
                || TextUtils.equals(data.getMsgType(), "6")) {
            if (TextUtils.equals(data.getMsgType(), "-1")) {
                PopWindowManager.showAsLocationWindow(praentView, commentContentView
                        , commentPopupWindow, R.id.comment_popwind_layout);
            }
            imMessage = MessageCreateUtils.sendTextMsg(data.getContent(), "",
                    data.getSenderType(), data.getSenderHeadImg()
                    , data.getSessionId(),
                    data.getSenderNickName(), data.getSenderId());
        } else {
            imMessage = MessageCreateUtils.sendMsg(data.getContent(), "",
                    data.getMsgType(), data.getSenderType(), data.getSenderHeadImg()
                    , data.getSessionId(),
                    data.getSenderNickName(), data.getSenderId());
        }

        notifyList(imMessage);
        showNotification(data.getContent(), data.getSenderNickName());
    }

    private static final int NOTIFICATION_FLAG = 3;

    public void showNotification(String content, String sendName) {
        if (TextUtils.equals(sendName, "0")) {
            sendName = "提示";
        }
        Bitmap bitmap = BitmapFactory.decodeResource(BaseApp.getContext().getResources(), R.mipmap.ic_launcher);
//        Intent intent = new Intent(this, NurseActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        Notification notify = new Notification.Builder(BaseApp.getContext())
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏中的小图片，尺寸一般建议在24×24
                .setLargeIcon(bitmap) // 这里也可以设置大图标
                .setTicker(BaseApp.getContext().getResources().getString(R.string.app_name)) // 设置显示的提示文字
                .setContentTitle(sendName) // 设置显示的标题
                .setContentText(content) // 消息的详细内容
                // .setNumber(1) // 在TextView的右方显示的数字，可以在外部定义一个变量，点击累加setNumber(count),这时显示的和
                .getNotification(); // 需要注意build()是在API level16及之后增加的，在API11中可以使用getNotificatin()来
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        NotificationManager manager = (NotificationManager) BaseApp.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_FLAG, notify);
        bitmap.recycle(); //回收bitmap
    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    //处理返回键
    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            //弹出提示，可以有多种方式
            ToastUtils.showShortToast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().finishAllActivity();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myConn != null) {
            unbindService(myConn);
        }

    }
}
